-module(growth).
-export([init/3]).
-include("cell_records.hrl").


init(NbNum, _Time, CPid) ->
  pause(NbNum, ?TIME, CPid).

pause(NbNum, Time, CPid) ->
  receive
    stop -> exit("stopped while paused");
    play -> loop(NbNum, Time, CPid);
    new_neighbor -> pause(NbNum + 1, Time, CPid);
    _ -> pause(NbNum, Time, CPid)
  end.

loop(NbNum, Time, CPid) ->
  receive
    pause -> pause(NbNum, Time, CPid);
    stop -> ok;
    new_neighbor -> loop(NbNum + 1, Time, CPid);
    print_all ->
      io:format("NbNum ~p Time ~p CPid ~p ~n", [NbNum, Time, CPid])
  after Time ->
    CPid ! check_veg_level,
    Veg = receive
      pause -> pause(NbNum, Time, CPid);
      {veg_status, Value} -> Value;
      stop -> exit("stopped while waiting for answer")
    end,
    if
      Veg >= 10000 ->
        loop(NbNum, Time, CPid);
      true ->
        AccVeg = get_veg_level(NbNum, 0, Time, CPid, NbNum),
        Boost = compute(NbNum, AccVeg, Veg),
        reply(CPid, Boost),
        loop(NbNum, Time, CPid)
    end
  end.

get_veg_level(0, Acc, _Time, _CPid, _NC) ->
  Acc;
get_veg_level(NbNum, Acc, Time, CPid, NC) ->
  receive
    pause -> pause(NC, Time, CPid);
    stop -> exit("stopped while waiting for answer");
    {reply_veg_level, Value} ->
      get_veg_level(NbNum - 1, Acc + Value, Time, CPid, NC)
  end.

compute(0, _Acc, _Veg) ->
  ?GROWTH;
compute(NbNum, Acc, Veg) ->
  Acc/NbNum - Veg.

reply(CPid, Value) when Value =< ?GROWTH ->
  CPid ! {boost_veg, ?GROWTH};
reply(CPid, Value) when Value < ?GROWTH * 5 ->
  CPid ! {boost_veg, Value};
reply(CPid, _Value) ->
  CPid ! {boost_veg, ?GROWTH * 5}.
